<template>
  <div v-if="isLongitudinal" class="componentContainer" v-drag>
    <el-dialog
      title="纵断面分析"
      style="width: 100%; pointer-events: auto"
      :modal="false"
      :close-on-click-modal="false"
      :visible.sync="isLongitudinal"
    >
      <template #title>
        <div class="custom-header drag-handle" style="font-size: 1rem; display: flex">
          <div class="bar" style="width: 5px; height: 20px; background-color: white; margin-right: 10px"></div>
          <span>纵断面分析</span>
        </div>
      </template>

      <!-- 图表容器 -->
      <div ref="chartRef" style="width: 100%; height: 300px; margin-bottom: 20px; background-color: #f5f5f5;"></div>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        v-loading="isLoading"
        element-loading-text="正在加载数据中..."
        style="width: 100%"
      >
        <el-table-column prop="keywords" label="关键字" width="90"></el-table-column>
        <el-table-column prop="type" label="管线类型" width="200"></el-table-column>
        <el-table-column prop="pipe_dia" label="管径"></el-table-column>
        <el-table-column prop="material" label="管材"></el-table-column>
        <el-table-column prop="brl_depth" label="埋深" width="100"></el-table-column>
        <el-table-column prop="start_brl_depth" label="起点埋深" width="100"></el-table-column>
        <el-table-column prop="end_brl_depth" label="终点埋深" width="100"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  data() {
    return {
      isLongitudinal: this.dialogVisible,
      chartInstance: null,
    };
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
    tableData: {
      type: Array,
      required: true,
    },
    isLoading: {
      type: Boolean,
      required: false,
    },
  },
  watch: {
    dialogVisible(newVal) {
      this.isLongitudinal = newVal;
      if (newVal) {
        this.$nextTick(() => {
          this.initChart();
        });
      }
    },
    tableData: {
      deep: true,
      handler() {
        this.updateChart();
      },
    },
  },
  mounted() {
    if (this.isLongitudinal) {
      this.$nextTick(() => {
        this.initChart();
      });
    }
  },
  methods: {
    initChart() {
      if (!this.$refs.chartRef) {
        console.error("Chart container not found!");
        return;
      }

      this.chartInstance = echarts.init(this.$refs.chartRef);

      const defaultOption = {
        backgroundColor: "#f5f5f5",
        title: {
          text: "纵断面分析图",
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            const labels = ["起点", "终点"];
            const index = params[0].dataIndex; // 获取当前点的索引
            const depth = Math.abs(params[0].value); // 获取当前点的埋深值
            const pipeDia = parseFloat(this.tableData[0].pipe_dia || 300); // 获取管径值（单位：mm）

            // 返回提示框的内容
            return `${labels[index]}埋深: ${depth} m<br>管径: ${pipeDia} mm`;
          }.bind(this), // 确保 this 指向正确
        },
        grid: {
          left: "5%", // 调整左侧间距
          right: "5%", // 调整右侧间距
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: ["起点", "终点"], // 只保留起点和终点
          boundaryGap: [0.1, 0.1], // 调整两侧空白区域
        },
        yAxis: {
          type: "value",
          min: -2.0, // 调整 Y 轴范围以适应负数埋深
          max: 0.5,
          interval: 0.2,
          axisLabel: {
            formatter: "{value} m",
          },
        },
        series: [
          {
            name: "管道顶部",
            type: "line",
            data: [], // 初始数据为空数组
            lineStyle: {
              color: "#2E8B57", // 管道顶部颜色
            },
            itemStyle: {
              color: "#2E8B57", // 点的颜色与线条一致
            },
          },
          {
            name: "管道底部",
            type: "line",
            data: [], // 初始数据为空数组
            lineStyle: {
              color: "#2E8B57", // 管道底部颜色（与顶部一致）
            },
            itemStyle: {
              color: "#2E8B57", // 点的颜色与线条一致
            },
            areaStyle: {
              color: "rgba(46, 139, 87, 0.3)", // 填充颜色（半透明）
            },
          },
          {
            name: "地面",
            type: "line",
            markLine: {
              data: [
                {
                  yAxis: 0, // 地面位置（0m）
                  lineStyle: {
                    color: "#000", // 地面线颜色
                    width: 2, // 地面线宽度
                  },
                  label: {
                    formatter: "地面", // 地面标识
                    position: "start", // 标签位置调整为起点
                  },
                },
              ],
            },
          },
        ],
      };

      this.chartInstance.setOption(defaultOption);
    },

    updateChart() {
      if (!this.tableData || this.tableData.length === 0) {
        console.warn("No data to update chart.");
        return;
      }

      // 设置埋深值
      this.$set(this.tableData[0], 'brl_depth', 0.5); // 中间点埋深（虽然未显示，但可能用于其他逻辑）
      this.$set(this.tableData[0], 'start_brl_depth', 0.75); // 起点埋深
      this.$set(this.tableData[0], 'end_brl_depth', 1); // 终点埋深

      // 计算管道顶部和底部数据
      const topData = [
        -parseFloat(this.tableData[0].start_brl_depth || 0), // 起点埋深
        -parseFloat(this.tableData[0].end_brl_depth || 0),   // 终点埋深
      ];

      const pipeDia = parseFloat(this.tableData[0].pipe_dia || 300) / 1000; // 管径转换为米（确保单位正确）
      const bottomData = topData.map((depth) => depth - pipeDia); // 底部数据 = 顶部数据 - 管径

      // 更新图表
      this.chartInstance.setOption({
        xAxis: {
          data: ["起点", "终点"], // 只保留起点和终点
        },
        series: [
          {
            name: "管道顶部",
            data: topData,
          },
          {
            name: "管道底部",
            data: bottomData,
          },
        ],
      });
    },
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  },
};
</script>

<style lang="scss" scoped>
.componentContainer {
  position: absolute;
  width: 50rem;
  height: 50rem;
  top: 0;
  left: -20vw;
  pointer-events: none;
}
::v-deep .el-dialog__wrapper {
  position: absolute !important;
  pointer-events: none !important;
}
::v-deep .el-dialog {
  background-color: #285383;
  pointer-events: none !important;
  .el-dialog__header {
    pointer-events: auto;
  }
  .el-dialog__body {
    pointer-events: auto;
  }
}
</style>